import logging
from .model import Hex

class GameContextDataStore:
  game_contexts = {}
    
  @classmethod
  def put(cls, game_context):
    cls.game_contexts[game_context.id] = game_context
    
  @classmethod
  def get(cls, game_context_id):
    if game_context_id in cls.game_contexts.keys():
      return cls.game_contexts[game_context_id]
    else:
      return None
  
  @classmethod
  def get_all(cls):
    return cls.game_contexts.values()

  @classmethod
  def get_all_players(cls): 
    return reduce(lambda x,y: x+y.players, cls.get_all(), [])

  @classmethod
  def get_game_headers(cls): 
    headers = []
    for game_context in cls.game_contexts.values(): 
      headers.append({"id":game_context.id,
                      "num_players":len(game_context.players)})
    return {'gamelist': headers}
  
  @classmethod
  def get_init_board(cls): 
    init_board = {'hex_to_vertex_map' : Hex.hex_to_vertex_map,
                  'vertex_to_hex_map' : Hex.vertex_to_hex_map,
                  'vertex_to_edge_map' : Hex.vertex_to_edge_map,
                  'edge_to_vertex_map' : Hex.edge_to_vertex_map,
                  'vertex_to_vertex_map' : Hex.vertex_to_vertex_map,
                  'edge_to_edge_map' : Hex.edge_to_edge_map,
                  }
    return init_board
  
  @classmethod
  def get_player_in_game(cls, token, game_context):
    player = None
    index = 0
    for p in game_context.players:
      if p.token == token:
        player = p
        break
      index += 1
    return [player, index]
  
  @classmethod
  def get_games_with_player(cls, token):
    games = []
    for game_id in cls.game_contexts.keys():
      [player, index] = cls.get_player_in_game(token, cls.game_contexts[game_id])
      if player != None:
        games.append(cls.game_contexts[game_id])
    return games
  
  @classmethod
  def delete_game(cls, game_context_id):
    logging.warning("deleting game with id %d" % game_context_id)
    del cls.game_contexts[game_context_id]

